import axios from 'axios'
import store from '@/store'
import notification from 'crec-ui/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { constant as errorCode, tools } from 'crec-common'
import debounce from 'lodash/debounce'
import Cookie from 'js-cookie'
let toastN = ({ message, description }) => {
  notification.error({
    message,
    description
  })
}
toastN = debounce(toastN, 500)

let baseURL = process.env.VUE_APP_PUBLIC_PATH + process.env.VUE_APP_API_BASE_URL
const initRequest = ({ requestBase = '' }) => {
  baseURL = requestBase + process.env.VUE_APP_PUBLIC_PATH + process.env.VUE_APP_API_BASE_URL
}
// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL,
  timeout: 60000 // 请求超时时间
})
// 异常拦截处理器
const errorHandler = error => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    if (error.response.status === 403) {
      notification.error({
        message: '被禁止',
        description: data.message
      })
    }
    if (error.response.status === 404) {
      notification.error({
        message: '接口未找到',
        description: `${data.path}`
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: '认证失效',
        description: '用户认证失败'
      })
    }
    if (error.response.status >= 500) {
      notification.error({
        message: '服务器错误',
        description: data.message || error.response.statusText
      })
    }
  }

  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  config.baseURL = baseURL
  const token = Cookie.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers.common.Authorization = `Bearer ${token}`
  }

  // config.headers.common.clientId = store.getters.client_Id || window.config.VUE_APP_CLIENT_ID || ''
  // config.headers.common.appId = store.getters.app_Id || window.config.VUE_APP_APP_ID || ''
  // config.headers.common.tenantId = store.getters.tenant_Id || window.config.VUE_APP_TENANT_ID || ''

  config.headers.common.clientId = process.env.VUE_APP_CLIENT_ID || ''
  config.headers.common.appId = process.env.VUE_APP_APP_ID || ''
  config.headers.common.tenantId = process.env.VUE_APP_TENANT_ID || ''

  config.headers.common.moudleId = window.localStorage.getItem('accessMoudleId') || ''
  config.headers.common.organId = window.localStorage.getItem('accessOrganId') || ''
  config.headers.common.organCode = window.localStorage.getItem('accessOrganCode') || ''

  if (config.method.toLowerCase() === 'get') {
    config.params = config.params || {}
    config.params.t = new Date().getTime()
  }
  if (store.getters.auth_pattern === 2) {
    config.headers.common.fullIdPath = window.localStorage.getItem('fullIdPath')
    config.headers.common.orgForm = window.localStorage.getItem('orgForm')
    config.headers.common.versionCode = window.localStorage.getItem('versionCode')
    config.headers.common.organName = encodeURI(window.localStorage.getItem('organName'))
  }
  console.log(config)
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use(response => {
  if (
    response.headers['content-type'] === 'application/octet-stream' ||
    response.headers['content-type'].indexOf('application/vnd.ms-excel') !== -1
  ) {
    const fileName = decodeURI(response.headers['content-disposition'].split(';')[1].split('=')[1] || '')
    return {
      res: response.data,
      fileName
    }
  }
  // 100401 /oauth/refreshToken为刷新token的接口, 需要排除掉
  if (response.data.code === errorCode.error.ERR_CODE_EXPIRE_TOKEN) {
    if (!response.config.url.includes('/oauth/refreshToken') && !response.config.url.includes('/oauth/logout')) {
      // refreshTokenPromise：获取token的promise，直接返回token；error为获取token失败的回调
      return tools.checkToken({
        response,
        request,
        refreshTokenPromise: () => {
          return store.dispatch('RefreshToken')
        },
        error: () => {
          store.dispatch('Logout')
        }
      })
    } else {
      store.dispatch('Logout')
    }
  }
  // 100404 排除登出接口
  if (response.data.code === errorCode.error.ERR_CODE_UNAUTHORIZED && !response.config.url.includes('/oauth/logout')) {
    toastN({
      message: response.data.message
    })
    setTimeout(() => {
      store.dispatch('Logout')
    }, 1500)
  }
  if ((response.data.code || +response.data.code === 0) && response.data.code !== errorCode.error.SUCCESS) {
    toastN({
      message: '错误提示',
      description: response.data.message || response.data.errmsg
    })
    return Promise.reject(response.data)
  }
  if (response.data.data) {
    return response.data.data
  } else if (response.data.data === 0) {
    return response.data.data
  } else {
    return response.data
  }
}, errorHandler)

request.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (
      (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) ||
      error.message.indexOf('Network Error') !== -1
    ) {
      toastN({
        message: '网络错误',
        description: '请检查网络再重新连接'
      })
      error.message = '请检查网络再重新连接'
      return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)
const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export { installer as VueAxios, request as axios, initRequest }
